// fetch.js的中间件，用于拦截ajax的请求

import fetch from './fetch';
import utils from './utils';
import storage from './storage';
import autoStorage from './autoStorage';
import encrypt from './encrypt';
const LOGIN_AESKEY = '1234567812345678';

// 格式化请求的url
function fmtURL(opts, next){
  let host = utils.getHost();
  opts.url = host + '/tomcat/new_ydsn' + opts.url + '.do';
  // opts.url = host + '/new_ydsn' + opts.url + '.do';
  // opts.url = 'http://localhost:8080' + opts.url + '.do';
  // opts.url = 'http://10.48.13.126:8080/new_ydsn' + opts.url + '.do';
  next(opts);
}

// 为请求添加统一的参数
function addRequestParams(opts, next){
  let ik = storage.getItem('ik');
  // 正则生成器
  const portArr = ['getCourseInfo', 'getKaoBiao',
    'getScore', 'lookMessage', 'tuiSong', 'commitView'];
  let regs = new RegExp('/(' + portArr.join('|') + ')');
  if(regs.test(opts.url)){
    opts.data['i'] = ik.i;
  }
  opts.data['version'] = window.APP_CONFIG.version;
  next(opts);
}

// 为请求统一加密
function encodeParams(opts, next){
  let ik = storage.getItem('ik');
  // const reg = /\/login/;
  let oData = opts.data;
  let aesKey = LOGIN_AESKEY;
  let param = new URLSearchParams();
  // if(!reg.test(opts.url)){
  // 用户标示
  if(opts.data.i){
    aesKey = ik.k;
    param.append('i', encodeURIComponent(encrypt.AES(ik.i, LOGIN_AESKEY)));
    // delete opts.data.i;
  }
  console.log(opts.url, aesKey, opts);
  let eData = encodeURIComponent(encrypt.AES(JSON.stringify(oData), aesKey));
  param.append("d", eData);
  // opts.data = {
  //   d: encodeURIComponent(encrypt.AES(JSON.stringify(oData), aesKey))
  // }
  opts.data = param;
  next(opts);
}

// 返回参数解密
function decodeParams(opts, next){
  let f = opts.success;
  opts.success = function(res){
    let ik = storage.getItem('ik');
    const reg = /\/login/;
    let aesKey = LOGIN_AESKEY;
    if(!reg.test(opts.url)){
      aesKey = ik.k;
    }
    let decodeData;
    let uriDecode = decodeURIComponent(res.data);
    // decodeData = encrypt.DAES(decodeURIComponent(res.data), aesKey);
    // console.log(res.data, aesKey)
    decodeData = encrypt.DAES(uriDecode, aesKey);
    console.log(uriDecode,decodeData);

    if(!decodeData){
      decodeData = encrypt.DAES(uriDecode, LOGIN_AESKEY);
    }

    res.data = JSON.parse(decodeData);
    console.log(res.data);
    // console.log(res);
    f && f(res);
    if(res.data.data){
      storage.setItem(opts.url, res.data.data);
    }
  }
  next(opts);
}

// 模拟数据
function getMockData(opts, next){
  const map = {
    'error': 'error.json', // 模拟404状态
    'error2': 'error2.json', // 接口对应地址不存在
    '/login': 'login.json', // 登录
    '/lookMessage': 'lookMessage.json', // 查看通知
    '/getCourseInfo': 'getCourseInfo.json', // 获取课表
    '/openingdate': 'openingdate.json', // 获取开学日期
    '/getScore': 'grades.json', // 获取成绩
    '/getKaoBiao': 'tests.json', // 获取考表
    '/getChaJianList': 'chajianList.json' // 获取插件列表
  }

  let data = {
    status:200,
    // 从服务器返回的http状态文本
    statusText:'OK',
    // 响应头信息
    headers: {},
    // `config`是在请求的时候的一些配置信息
    config: {}
  }

  let isMockError = true;
  let isError = false;
  let isPathExist = true;

  let filename = map[opts.url];
  let rand;
  if(isMockError){
    rand = Math.round(Math.random() * 10);
    if(rand === 9){
      isError = true;
    }
  }

  if(!filename){
    filename = map['error2'];
    isPathExist = false;
  }
  if(isPathExist){
    if(isError){
      filename = map['error'];
      data.status = 404;
      data.statusText = 'Not Found';
    }
  }
  let json = require('../json/' + filename);
  data.data = JSON.parse(JSON.stringify(json));
  setTimeout(() => {
    if(isError){
      opts.error && opts.error(data);
    }else{
      opts.success && opts.success(data);
    }
  }, 1000);

  next(opts, 'break');
}

export default function addFetchMiddleware(){
  if(!window.APP_CONFIG.isDebug){
    fetch.use(decodeParams); // 返回参数自动解密
    fetch.use(addRequestParams); // 为请求添加公共参数
  }
  fetch.use(autoStorage); // 请求自动储存
  if(window.APP_CONFIG.isDebug){
    fetch.use(getMockData); // 是否模拟数据
  }
  fetch.use(fmtURL); // 根据网络环境自动选择请求url
  fetch.use(encodeParams); // 请求参数加密
  // fetch.use(addExt);
}
